package cn.com.mayue.guava.io;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by mayue on 2017/4/5.
 * guava io测试
 * copy  equal
 */
public class IoTest {

    /**
     * 复制的文件 比较是相同的，但是读取再写入 是不同的
     * @throws IOException
     */
    @Test
    public void testEqual() throws IOException {
        String fileNameOne = "E:/mayue/selfPro/javaDemo/target/classes/test.txt";
        String fileNameTwo = "E:/test.txt";
        System.out.println(Files.equal(new File(fileNameOne),new File(fileNameTwo)));
    }

    @Test
    public void testTouch() throws IOException {
        File file = new File("E:/mayue/selfPro/javaDemo/target/classes/test" + UUID.randomUUID().toString() + ".txt");
        Files.touch(file);
    }

    @Test
    public void test() {
        try {
            File readFile = new File("E:/mayue/selfPro/javaDemo/target/classes/test.txt");
            StringBuilder content = new StringBuilder();
            if (readFile.exists()) {
                List<String> lines = readFile(readFile);
                for (String string : lines) {
                    System.out.println(string);
                    content.append(string + "\n");
                }
            }
            File writeFile = new File("E:/mayue/selfPro/javaDemo/target/classes/test" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".txt");
            writeFile(content.toString(), writeFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static List<String> readFile(File file) throws Exception {
        if (!file.exists()) {
            return null;
        }
        return Files.readLines(file, Charsets.UTF_8);
    }

    public List<String[]> readFileData(File file) throws Exception {
        List<String[]> list = new ArrayList<String[]>();
        for (String rLine : readFile(file)) {
            list.add(rLine.split("\\s+"));
        }
        return list;
    }


    private static void writeFile(String content, File file) throws Exception {
        if (!file.exists()) {
            file.createNewFile();
        }
        Files.write(content, file, Charsets.UTF_8);
    }
}
